using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Server.DTOs;
using Server.Services;
using System.ComponentModel.DataAnnotations;

namespace Server.Controllers
{
    [Route("api/file")]
    [ApiController]
    public class FtpController : ControllerBase
    {
        private readonly IFtpService _ftpService;
        private readonly ILogger<FtpController> _logger;

        public FtpController(IFtpService ftpService, ILogger<FtpController> logger)
        {
            _ftpService = ftpService;
            _logger = logger;
        }

        /// <summary>
        /// 验证用户上传权限并返回FTP凭证
        /// </summary>
        /// <param name="uploadInfo">上传信息</param>
        /// <returns>FTP上传凭证</returns>
        [HttpPost("verify-upload")]
        public async Task<ActionResult<Server.DTOs.FtpUploadCredentials>> VerifyUploadPermissionAsync([FromBody][Required] Server.DTOs.UploadInfo uploadInfo)
        {
            try
            {
                _logger.LogInformation("收到验证上传权限请求");
                var credentials = await _ftpService.VerifyUploadPermissionAsync(uploadInfo);

                if (credentials != null)
                {
                    _logger.LogInformation("验证成功，返回FTP凭证");
                    return Ok(credentials);
                }
                else
                {
                    _logger.LogWarning("验证失败，拒绝访问");
                    return Unauthorized(new { Message = "用户不存在或无权限上传" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证上传权限时发生异常");
                return StatusCode(500, new { Message = "服务器内部错误" });
            }
        }

        /// <summary>
        /// 验证用户下载权限并返回FTP凭证
        /// </summary>
        /// <param name="fileInfo">文件信息</param>
        /// <returns>FTP下载凭证</returns>
        [HttpPost("verify-download")]
        public async Task<ActionResult<Server.DTOs.FtpUploadCredentials>> VerifyDownloadPermissionAsync([FromBody][Required] Server.DTOs.FileInfo fileInfo)
        {
            try
            {
                _logger.LogInformation("收到验证下载权限请求");
                var credentials = await _ftpService.VerifyDownloadPermissionAsync(fileInfo);

                if (credentials != null)
                {
                    _logger.LogInformation("验证成功，返回FTP凭证");
                    return Ok(credentials);
                }
                else
                {
                    _logger.LogWarning("验证失败，拒绝访问");
                    return Unauthorized(new { Message = "用户不存在或无权限下载" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证下载权限时发生异常");
                return StatusCode(500, new { Message = "服务器内部错误" });
            }
        }
    }
}